package com.oitsm.utils;

import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

/**
 * JSON工具
 * @author Arab Runner
 * Jun 25, 2011 11:56:26 AM
 */
public class JSONUtils {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

	}
	
	public static void putResultFlag(JSONObject jo,boolean flag){
		jo.put("success", flag);
	}
	
	public static void putFailureFlag(JSONObject jo){
		putResultFlag(jo,false);
	}
	
	public static void writeSuccessJSON(HttpServletResponse res)throws Exception{
		writeResultJSON(res,true,null);
	}
	
	public static void putSuccessFlag(JSONObject jo){
		putResultFlag(jo,true);
	}
	
	public static void writeFailureJSON(HttpServletResponse res)throws Exception{
		writeResultJSON(res,false,null);
	}
	
	public static void writeResultJSON(HttpServletResponse res,boolean success,Map<String,Object> props)throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("success", success);
		if(props!=null){
			for(String key : props.keySet()){
				jo.put(key, props.get(key));
			}
		}
		write(res,jo.toString());
	}
	
	public static void write(HttpServletResponse res,String text)throws Exception{
		res.setCharacterEncoding("UTF-8");
		res.getWriter().print(text);
		res.getWriter().flush();
	}

}
